<template>
  <div>
    <el-upload list-type="picture-card"
               action=""
               :http-request="upload"
               :on-preview="handlePictureCardPreview"
               :on-remove="handleRemove"
               :on-change="handleChange"
               :file-list="fileList"
               :limit="limit"
               :before-upload="beforeUpload"
               :class="{hidden: fileList.length >= limit}">
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible.sync="showDialog"
               title="图片预览"
               width="40%">
      <img style="width: 100%; height: 600px;object-fit: cover;"
           :src="imgUrl"
           alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  name: 'ImageUpload',
  props: {
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      imgUrl: '',
      showDialog: false,
      // 组件默认需要显示的图片
      fileList: [
        // {
        //   url: 'https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3363295869,2467511306&fm=26&gp=0.jpg'
        // },
        // {
        //   url: 'https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2771978851,2906984932&fm=26&gp=0.jpg'
        // }
      ]
    }
  },
  created() {
    this.cos = new COS({
      SecretId: 'AKIDvdOzNe2P00qTvGS6IMKC1sc8NQTVuH5i',
      SecretKey: 'DsIWgjrBNOYgMZbU7rgJBXnJgpmX5oTa'
    })
  },
  methods: {
    upload({ file }) {
      this.cos.putObject({
        Bucket: 'hr-83-1256173530', /* 必须 */
        Region: 'ap-shanghai', /* 存储桶所在地域，必须字段 */
        // 文件名
        Key: Date.now() + '-' + parseInt(Math.random() * 1000) + '-' + file.name, /* 必须 */
        StorageClass: 'STANDARD',
        // 文件
        Body: file // 上传文件对象
      }, (err, data) => {
        if (err) return this.$message.error(err)
        console.log('上传的结果', data)
        const result = this.fileList.find(item => item.uid === file.uid)
        result.status = 'success'
        result.url = 'http://' + data.Location
      })
    },
    handlePictureCardPreview(file) {
      this.imgUrl = file.url
      this.showDialog = true
    },
    //删除图片
    // file: 删除的那个文件
    // fileList: 剩下的文件列表
    handleRemove(file, fileList) {
      //console.log('图片删除了', fileList)
      this.fileList = fileList
    },
    // 添加图片
    handleChange(file, fileList) {
      //console.log('图片改变了', fileList)
      this.fileList = fileList
    },
    // 上传图片 检查
    beforeUpload(file) {
      // 校验文件必须是图片  gif png jpg
      if (!['image/png', 'image/jpeg'].includes(file.type)) {
        this.$message.error('请上传正确格式的图片')
        return false
      }
      if (file.size >= 1024 * 1024 * 1) {
        this.$message.error('请不要上传超过1M的图片')
        return false
      }
      return true
    }
  }
}
</script>

<style lang="scss" scoped>
.hidden {
  ::v-deep {
    .el-upload--picture-card {
      display: none;
    }
  }
}
</style>
